//
//  ZMJAudioPlayTool.m
//  Z-QQMusic
//
//  Created by zmj on 15/11/5.
//  Copyright © 2015年 zmj. All rights reserved.
//

#import "ZMJAudioTool.h"

@implementation ZMJAudioTool
static NSMutableDictionary * musicPlayerDict_;/**< 存放@{音频名:player}的字典 */
static AVAudioPlayer *currentPlayer_;
/**
 *  初始化存放播放器字典
 */
+ (void)initialize
{
    musicPlayerDict_ = [NSMutableDictionary dictionary];
}
/**
 *  播放本地音频
 *
 *  @param musicName 音频在本地路径中的全称(包括音频类型)
 *
 *  @return 播放该音频的player
 */
+ (AVAudioPlayer *)playingMusicWithName:(NSString *)musicName {
    // 0.判断传入的字符串是否为空
    assert(musicName);
    
    // 1.从字典中取出播放器
    AVAudioPlayer *player = musicPlayerDict_[musicName];
    
    // 2.如果取出为空,则创建对应的播放器
    if (player == nil) {
        // 2.1.获取音乐对应的URL
        NSURL *url = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];
        
        // 2.2.创建对应的播放器
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        
        // 2.3.将播放器存到字典中
        [musicPlayerDict_ setObject:player forKey:musicName];
    }
    
    // 3.播放音乐
    [player prepareToPlay];
    [player play];
    currentPlayer_ = player;
    return player;
}


/**
 *  停止播放音乐,并且当前播放进度清0
 *
 *  @param musicName 音乐名
 */
+ (void)stopMusicWithMusicName:(NSString *)musicName {
    // 0.判断传入的字符串是否为空
    assert(musicName);
    
    // 1.取出对应的播放器
    AVAudioPlayer *player = musicPlayerDict_[musicName];
    
    // 2.停止播放
    if (player) {
        [player stop];
        [musicPlayerDict_ removeObjectForKey:musicName];
        player = nil;
    }
}










@end
